package com.whfc.fvs.service.manager;

import com.whfc.common.file.FileHandler;
import com.whfc.common.file.FilePathConfig;
import com.whfc.common.util.ImageUtil;
import com.whfc.fvs.dao.FvsDeviceMapper;
import com.whfc.fvs.dao.FvsSnapshotMapper;
import com.whfc.fvs.dto.FvsDeviceDTO;
import com.whfc.fvs.entity.FvsDevice;
import com.whfc.fvs.entity.FvsSnapshot;
import com.whfc.fvs.enums.FvsDeviceStatus;
import com.whfc.fvs.enums.FvsDeviceType;
import com.whfc.fvs.enums.VsPlatform;
import com.whfc.fvs.service.FvsPlatformService;
import com.whfc.fvs.service.factroy.FvsPlatformServiceFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.net.URL;
import java.util.*;

/**
 * 视频mgr
 *
 * @author xugcheng
 * @version 1.0
 * @date 2021-09-30 14:57
 */
@Component
public class FvsSnapshotMgr {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private FileHandler fileHandler;

    @Autowired
    private FilePathConfig filePathConfig;

    @Autowired
    private FvsSnapshotMapper fvsSnapshotMapper;

    @Autowired
    private FvsDeviceMapper fvsDeviceMapper;

    @Autowired
    private FvsPlatformServiceFactory platformServiceFactory;


    /**
     * 项目视频抓拍
     *
     * @param deptId 组织架构ID
     */
    public void createSnapshot(Integer deptId) {

        //萤石云抓图
        this.createSnapshot(deptId, VsPlatform.HIK_EZVIZ);

        //乐橙云抓图
        this.createSnapshot(deptId, VsPlatform.DAHUA_IMOU);
    }

    /**
     * 项目视频抓拍
     *
     * @param deptId     组织架构ID
     * @param vsPlatform 监控平台
     */
    public void createSnapshot(Integer deptId, VsPlatform vsPlatform) {
        try {

            List<FvsDeviceDTO> deviceList = fvsDeviceMapper.selectByDeptIdAndPlatform(deptId, Collections.singletonList(vsPlatform.getValue()));
            List<FvsSnapshot> snapshotList = new ArrayList<>(deviceList.size());
            FvsPlatformService platformService = platformServiceFactory.getFvsPlatFromService(vsPlatform);
            Date now = new Date();
            for (FvsDeviceDTO fvsDeviceDTO : deviceList) {
                Integer deviceStatus = fvsDeviceDTO.getDeviceStatus();
                //设备离线跳过抓图
                if (FvsDeviceStatus.OFFLINE.getValue().equals(deviceStatus)) {
                    continue;
                }
                //抓图
                String snapshotUrl = platformService.getSnapshotUrl(fvsDeviceDTO);
                if (StringUtils.isEmpty(snapshotUrl)) {
                    continue;
                }
                //抓图上传
                String urlPath;
                try {
                    //上传视频截图到oss
                    String fileName = fvsDeviceDTO.getId() + ".png";
                    String ossKey = filePathConfig.getFilePath("fvs/snapshot/capture", deptId + "/" + fileName);
                    urlPath = fileHandler.upload(ossKey, new URL(snapshotUrl).openStream());
                } catch (Exception e) {
                    logger.warn("上传图片失败.");
                    continue;
                }
                if (StringUtils.isEmpty(urlPath)) {
                    continue;
                }
                //创建快照
                FvsSnapshot fvsSnapshot = new FvsSnapshot();
                fvsSnapshot.setDeptId(fvsDeviceDTO.getDeptId());
                fvsSnapshot.setDeviceId(fvsDeviceDTO.getId());
                fvsSnapshot.setDeviceName(fvsDeviceDTO.getName());
                fvsSnapshot.setTime(now);
                fvsSnapshot.setSnapshotUrl(urlPath);
                snapshotList.add(fvsSnapshot);
            }
            //保存快照
            if (!snapshotList.isEmpty()) {
                fvsSnapshotMapper.batchInsert(snapshotList);
            }
        } catch (Exception ex) {
            logger.warn("视频抓图失败", ex);
        }
    }

    /**
     * 更新视频设备封面
     *
     * @param vsPlatform 监控平台
     */
    public void updateDeviceSnapshot(VsPlatform vsPlatform) {
        logger.info("更新监控封面, platform:{}", vsPlatform.getDesc());
        FvsPlatformService platFromService = platformServiceFactory.getFvsPlatFromService(vsPlatform);
        //获取所有设备
        List<FvsDeviceDTO> deviceList = fvsDeviceMapper.selectByPlatform(vsPlatform.getValue());
        for (FvsDeviceDTO fvsDeviceDTO : deviceList) {
            if (FvsDeviceType.DVR.getValue().equals(fvsDeviceDTO.getDeviceType())) {
                // 跳过硬盘录像机
                continue;
            }
            try {
                String snapshotUrl = platFromService.getSnapshotUrl(fvsDeviceDTO);
                if (!StringUtils.isEmpty(snapshotUrl)) {
                    // 图片压缩
                    // 默认视频封面截图压缩大小
                    int desFileSize = 100;
                    InputStream inputStream = ImageUtil.compressPicForScale(ImageUtil.getFileStream(snapshotUrl), desFileSize);
                    //图片上传
                    String fileName = fvsDeviceDTO.getId() + ".png";
                    String ossKey = filePathConfig.getFilePath("fvs/snapshot/image", fileName);
                    String fileUrl = fileHandler.upload(ossKey, inputStream);
                    //保存封面
                    FvsDevice fvsDevice = new FvsDevice();
                    fvsDevice.setId(fvsDeviceDTO.getId());
                    fvsDevice.setSnapshotUrl(fileUrl + "?" + System.currentTimeMillis());
                    fvsDeviceMapper.updateByPrimaryKeySelective(fvsDevice);
                }
            } catch (Exception ex) {
                logger.error("抓取图片出现异常", ex);
            }
        }
    }
}
